(function () {
  function set_store(k, v) {
    chrome.storage.sync.set({ [k]: v }, function () {
      // console.log('保存成功！');
    });
  }
  function get_store(k, callback) {
    chrome.storage.sync.get({ [k]: '' }, callback);
  }
  function get_bookmarks(callback) {
    chrome.bookmarks.getTree(e => {
      callback(e[0].children)
    })
  }
  function translate(e) {
    // 有道翻译
    $.ajax({
      url: 'http://fanyi.youdao.com/translate',
      method: 'get',
      data: {
        'doctype': 'json',
        type: 'auto',
        i: e
      },
      dataType: 'json',
      success: function (res) {
        console.log(res, "suc")
        if (res.errorCode == 0) {
          console.log("ssssss", res.translateResult[0][0].tgt, back)
          back(res.translateResult[0][0].tgt)
        } else {
          console.log("res.code不为0")
          back("res.code不为0")
        }
      },
      error(err) {
        console.log(err, "err")
      },
      complete: function (res) {
        console.log(res, "com")
      }
    })
    //腾讯云翻译
    /*  $.ajax({
       url:'https://tmt.tencentcloudapi.com/',
       data:{
         Action:'TextTranslate',
         Version:'2018-03-21',
         Region:'ap-guangzhou-open',
         Timestamp:+new Date(),
         Nonce:parseInt(Math.random()*1000+1),
         SecretId:'AKIDH6g7JjNKEsjKj2fHdiYbOuiMtAuTjTYN',
         
   
         ProjectId:0,
         Source:'en',
         Target:'zh',
         SourceText:e
       },
       method: 'get',
       dataType: 'json',
       success: res=>{
         console.log(res,"yyyyy")
       }
   
     }) */
  }

  //判断两个对象是否相同
  /* function Compare(objA, objB) {
    function getType(data) {
      return Object.prototype.toString.call(data).substring(8).split(/]/)[0]
  } */

  function getType(data) {
    return Object.prototype.toString.call(data).substring(8).split(/]/)[0]
  }
  function Compare(sourceObj, compareObj) {
    let arr = []
    if (arguments.length < 2) throw "Incorrect number of parameters";
    let sourceType = getType(sourceObj);
    if (sourceType !== getType(compareObj)) return false;
    // Not objects and arrays
    if (sourceType !== "Array" && sourceType !== "Object" && sourceType !== "Set" && sourceType !== "Map") {
      if (sourceType === "Number" && sourceObj.toString() === "NaN") {
        return compareObj.toString() === "NaN"
      }
      return sourceObj === compareObj
    } else if (sourceType === "Array") {
      if (sourceObj.length !== compareObj.length) return false;
      if (sourceObj.length === 0) return true;
      for (let i = 0; i < sourceObj.length; i++) {
        if (!Compare(sourceObj[i], compareObj[i])) return false;
      }
    } else if (sourceType === "Object") {
      let sourceKeyList = Reflect.ownKeys(sourceObj);
      let compareKeyList = Reflect.ownKeys(compareObj);
      let key;
      if (sourceKeyList.length !== compareKeyList.length) return false;
      for (let i = 0; i < sourceKeyList.length; i++) {
        key = sourceKeyList[i];
        if (key !== compareKeyList[i] && arr.indexOf(key) > -1) return false;
        if (!Compare(sourceObj[key], compareObj[key]) && arr.indexOf(key) > -1) return false;
      }
    } else if (sourceType === "Set" || sourceType === "Map") {
      // 把 Set Map 转为 Array
      if (!Compare(Array.from(sourceObj), Array.from(compareObj))) return false;
    }
    return true;
  }
  //删除重写本地标签
  var t= this;
  async function pullBookmarks(json) {
    console.log('pullBookmarks   删除重写本地书签',json,t,this,t.lock_listener)
    t.lock_listener = true
    await (function(){
      for(let i = 0;i<2;i++){
        get_bookmarks(res => {
          let arr_other = res[i].children;
          for (let k in arr_other) {
            t.lock_listener=true/* ,console.log(t.lock_listener,"lllll") */
            chrome.bookmarks.removeTree(String(arr_other[k].id), res => {
              console.log(res, "remove", json, json[i])
            })
          }
        })
      }
    })();
    console.log('pullBookmarks    删除完成,开始写入')
    arrow(json[0].children, json[0].id);
    arrow(json[1].children, json[1].id);
    t.lock_listener=false;
    console.log("pullBookmarks     写入完成")
  }

  function arrow(json, pid) {
    console.log("arrow", json, pid)
    for (let k in json) {
      // console.log('json[k] parent', json[k])
      if (json[k].children) {
        chrome.bookmarks.create({
          parentId: pid,
          index: json[k].index,
          title: json[k].title,
          url: null
        }, res => {
          arrow(json[k].children, json[k].id);
        })
      } else {
        // console.log('json[k] son', json[k])
        chrome.bookmarks.create({
          parentId: pid,
          index: json[k].index,
          title: json[k].title,
          url: json[k].url
        }, res => {
        })
      }
    }
  }
  function send(key,value, callback) {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {[key]:value}, function (res) {
        if (callback) callback(res);
      });
    });
  }
  this.send = send;
  this.lock_listener = false;
  this.set_store = set_store;
  this.get_store = get_store;
  this.get_bookmarks = get_bookmarks;
  this.translate = translate;
  this.Compare = Compare;
  this.pullBookmarks = pullBookmarks;
})()